package com.dstation.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dstation.domain.ClassificationInfo;
import com.dstation.domain.UserInfo;
import com.dstation.domain.VideoInfo;
import com.dstation.service.interf.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    final int pageSize=10;

    @Autowired
    private IUserService userService;

    @Autowired
    private IClassificationService classificationService;

    @Autowired
    private IVideoService videoService;

    @Autowired
    private IRecommendService recommendService;

    @Autowired
    private IDynamicService dynamicService;

    @Autowired
    private IFollowTableService followTableService;
    /**
     * 进入登录界面
     * @return
     */
    @RequestMapping(value = "/userLoginPage")
    public String userLoginPage() {
        return "user/loginAndRegister";
    }

    /**
     * 进入个人设置界面
     * @return
     */
    @RequestMapping(value = "/userAccountPage")
    public String userAccountPage(ModelMap modelMap,HttpSession session) {
        modelMap.put("userInfo",session.getAttribute("userInfo"));
        return "main/userAccount";
    }

    @RequestMapping(value = "/userRegister")
    @ResponseBody
    public JSONObject userRegister(UserInfo userInfo) {

        JSONObject jsonResult = new JSONObject();
        boolean isExist = userService.findUserPhoneIsExistByPhone(userInfo.getUserPhone());
        if (isExist == true) {   //已经存在该手机号
            jsonResult.put("isExist", true);
            return jsonResult;
        } else {
            jsonResult.put("isExist", false);
            boolean saveResult = userService.addUserInfo(userInfo); //添加用户
            if (saveResult == true) {
                jsonResult.put("saveResult", true);
            } else {
                jsonResult.put("saveResult", false);
            }
            return jsonResult;
        }
    }

    /**
     * 用户登录
     * @param userInfo
     * @return
     */
    @RequestMapping(value = "/userLogin")
    @ResponseBody
    public JSONObject userLogin(UserInfo userInfo, HttpSession session) {
        JSONObject jsonResult = new JSONObject();
        UserInfo queryUserInfo = userService.findUserInfo(userInfo);
        if (queryUserInfo == null) {
            jsonResult.put("isExist", false);
        } else {
            session.setAttribute("userInfo", queryUserInfo);
            jsonResult.put("isExist", true);
        }
        return jsonResult;
    }

    @RequestMapping(value = "/userHomePage")
    public String userHomePage(@PathParam("page")Integer page, ModelMap modelMap, HttpSession session) {
        if(Objects.isNull(page)){
            page=1;
        }

        List<ClassificationInfo> classificationInfoList = classificationService.findAllChildClassification();   //查看全部的分类
        List<VideoInfo> videoInfoList = videoService.findAllVideoInfoByExamineStatusAccess();   //查询已经通过的视频
        IPage<VideoInfo> recommentVideoList = null;
        List<VideoInfo> noticedUserVideoList = null;

        UserInfo userInfo=(UserInfo) session.getAttribute("userInfo");

        recommentVideoList=recommendService.findRecommendVideo(userInfo,new Page(page,pageSize));


        noticedUserVideoList = followTableService.findFollowVideo(userInfo);



        modelMap.put("recommentVideoList", recommentVideoList); // 智能推荐的视频
        modelMap.put("noticedUserVideoList", noticedUserVideoList); // 智能推荐的视频
        modelMap.put("classificationInfoList", classificationInfoList);
        modelMap.put("videoInfoList", videoInfoList);
        return "main/home_login";
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("userInfo");
        return "user/loginAndRegister";
    }

    /**
     * 进入用户主界面
     * @return
     */
    @RequestMapping("/userMainPage")
    public String userMainPagec(@RequestParam("userId")Long userId,
                                ModelMap modelMap) {
        //1. 查询被查看用户主页信息
        UserInfo userInfo = userService.findUserInfoByUserId(userId);
        //2. 查询粉丝数量
        int followNum = userService.findFansNumByUserId(userId);
        //3. 查询该用户的全部视频信息
        List<VideoInfo> videoInfoList = videoService.findAllVideoInfoByExamineStatusAccessByUserId(userId);
        //4.查询该用户的全部动态信息(暂时没写)
        modelMap.put("userInfo", userInfo);
        modelMap.put("followNum", followNum);
        if(videoInfoList.size() == 0) {
            modelMap.put("videoInfoList", null);
        } else {
            modelMap.put("videoInfoList", videoInfoList);
        }


        return "main/userMainPage";
    }

    @RequestMapping(value = "/uploadImage")
    @ResponseBody
    public void uploadImage(@RequestBody MultipartFile file) {
        //判断文件是否存在
        if (file == null) {
            throw new RuntimeException("文件不存在");
        }
        //获取文件的完整名称
        String originalFilename = file.getOriginalFilename();
        String filePath = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\userIcon\\";
        File dest = new File(filePath + originalFilename);
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改个人资料
     * @return
     * */
    @RequestMapping(value = "/modifyUserInfo")
    @ResponseBody
    public JSONObject modifyUserInfo(@RequestBody Map<String,Object> map, HttpSession session) throws ParseException {
        JSONObject json = new JSONObject();
        UserInfo userInfo = new UserInfo();
        //将session中的用户信息存入新的userInfo
        UserInfo preUserInfo = (UserInfo)session.getAttribute("userInfo");
        userInfo.setUserId(preUserInfo.getUserId());
        userInfo.setUserPassword(preUserInfo.getUserPassword());
        userInfo.setUserBalance(preUserInfo.getUserBalance());
        userInfo.setPrivilegetimes(preUserInfo.getPrivilegetimes());

        userInfo.setUserName(String.valueOf(map.get("userName")));
        //判断手机号是否已经被注册
        String phone = preUserInfo.getUserPhone();
        if (!phone.equals(String.valueOf(map.get("userPhone")))){
            boolean isExist = userService.findUserPhoneIsExistByPhone(String.valueOf(map.get("userPhone")));
            if (isExist){
                json.put("res","-1");
                return json;
            }
        }
        userInfo.setUserPhone(String.valueOf(map.get("userPhone")));
        if (String.valueOf(map.get("userGender")).equals("true")){
            userInfo.setUserGender(true);
        }else{
            userInfo.setUserGender(false);
        }
        Timestamp time = new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(map.get("userBirthday"))).getTime());
        userInfo.setUserBirthday(time);
        userInfo.setUserSignature(String.valueOf(map.get("userSignature")));
        userInfo.setUserIcon(String.valueOf(map.get("userIcon")));
        boolean modifyResult = userService.alterUserInfo(userInfo);
        if (modifyResult){
            json.put("res","1");
            session.removeAttribute("userInfo");
            session.setAttribute("userInfo",userInfo);
        }else{
            json.put("res","0");
        }
        return json;
    }

}
